package com.joolun.web.controller.script;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joolun.common.core.domain.R;
import com.joolun.script.entity.CommonConfig;
import com.joolun.script.entity.WxUserExt;
import com.joolun.script.service.CommonConfigService;
import com.joolun.script.service.WxUserExtService;
import com.joolun.web.vo.WxUserVO;
import com.joolun.weixin.entity.WxUser;
import com.joolun.weixin.service.WxUserService;
import com.joolun.weixin.utils.ThirdSessionHolder;
import com.joolun.weixin.utils.WxMaUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 通用配置
 *
 * @author zkk
 * @date 2022-01-12 15:55:36
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/commonconfig")
@Api(value = "commonconfig", tags = "通用配置管理")
public class CommonConfigController {

    private final CommonConfigService commonConfigService;

    private final WxUserService wxUserService;

    private final WxUserExtService wxUserExtService;

    /**
     * 用户管理
     *
     * @param page   分页对象
     * @param wxUser 微信用户
     * @return
     */
    @ApiOperation(value = "用户管理")
    @GetMapping("/page")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(paramType = "query", dataType = "com.baomidou.mybatisplus.extension.plugins.pagination.Page"),
            @ApiImplicitParam(paramType = "query", dataType = "com.joolun.weixin.entity.WxUser"),
            @ApiImplicitParam(paramType = "query", required = true, name = "ascs", value = "升序字段参数 ascs | descs 任选其一或者混用都可，但是要注意顺序会影响排序结果", dataType = "String"),
            @ApiImplicitParam(paramType = "query", required = true, name = "descs", value = "降序字段参数 ascs | descs 任选其一或者混用都可，但是要注意顺序会影响排序结果", dataType = "String")
    }
    )
    public R<Page<WxUserVO>> getWxUserPage(Page<WxUser> page, WxUser wxUser) {
        Boolean isAdmin = ThirdSessionHolder.getThirdSession().getIsAdmin();
        if (!isAdmin) {
            return R.failed("没有权限");
        }

        Wrapper<WxUser> queryWrapper;
        if (StrUtil.isNotBlank(wxUser.getNickName())) {
            String nickName = wxUser.getNickName();
            wxUser.setNickName(null);
            queryWrapper = Wrappers.lambdaQuery(wxUser)
                    .like(WxUser::getNickName, nickName);
        } else {
            queryWrapper = Wrappers.lambdaQuery(wxUser);
        }
        page = wxUserService.page(page, queryWrapper);

        Page<WxUserVO> voPage = new Page<>();
        voPage.setCurrent(page.getCurrent());
        voPage.setSize(page.getSize());
        voPage.setPages(page.getPages());
        voPage.setTotal(page.getTotal());
        voPage.setOrders(page.orders());
        voPage.setRecords(Collections.emptyList());

        List<WxUser> records = page.getRecords();

        if (CollectionUtils.isEmpty(records)) {
            return R.ok(voPage);
        }

        LinkedList<WxUserVO> voList = new LinkedList<>();
        List<String> userIdList = records.stream().map(WxUser::getId).collect(Collectors.toList());
        Map<String, WxUserExt> extMap = wxUserExtService.getExtMap(wxUserExtService.queryByUserIdList(userIdList));
        records.forEach(record -> {
            WxUserVO vo = new WxUserVO();
            BeanUtils.copyProperties(record, vo);
            WxUserExt ext = extMap.get(record.getId());
            if (Objects.nonNull(ext)) {
                vo.setExt(ext);
            }
            voList.add(vo);
        });

        voPage.setRecords(voList);
        return R.ok(voPage);
    }

    /**
     * 原生配置
     *
     * @param commonConfig 通用配置
     * @return
     */
    @ApiOperation(value = "原生配置")
    @GetMapping
    @ApiImplicitParams(value = {
            @ApiImplicitParam(paramType = "query", name = "commonConfig", value = "通用配置参数", dataType = "com.joolun.script.entity.CommonConfig")}
    )
    public R<String> getPage(CommonConfig commonConfig) {
        return R.ok(commonConfigService.queryByModuleAndKey(commonConfig.getModule(), commonConfig.getKey()));
    }


    /**
     * 查询邮箱
     *
     * @return
     */
    @ApiOperation(value = "查询邮箱")
    @GetMapping("/email")
    public R<String> getEmail(HttpServletRequest request) {
        return R.ok(commonConfigService.queryEmail());
    }

    /**
     * 修改邮箱
     *
     * @param commonConfig 邮箱
     * @return
     */
    @ApiOperation(value = "修改邮箱")
    @PutMapping("/email")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(paramType = "query", name = "commonConfig", value = "通用配置参数", dataType = "com.joolun.script.entity.CommonConfig")}
    )
    public R<String> modify(HttpServletRequest request, CommonConfig commonConfig) {
        Boolean isAdmin = ThirdSessionHolder.getThirdSession().getIsAdmin();
        if (!isAdmin) {
            return R.failed("没有 修改邮箱 权限");
        }
        String appId = WxMaUtil.getAppId(request);
        Assert.hasText(commonConfig.getValue(), "邮箱不能为空");
        return R.ok(commonConfigService.saveV2(appId, commonConfig.getValue()));
    }

}
